package com.zhenyi.mongo.core;

import org.mongodb.morphia.Datastore;
import org.mongodb.morphia.Key;
import org.mongodb.morphia.Morphia;

import com.jfinal.kit.PropKit;
import com.mongodb.MongoClient;

import cn.hutool.core.lang.Singleton;

public class MongoUtils {
	Datastore datastore;

	private String HOST = PropKit.get("MONGO_HOST", "dev.zhen-yee.com");
	private String SCHEME = PropKit.get("MONGO_SCHEME", "pxlm");
	private String PACKAGE = PropKit.get("MONGO_PACKAGE", "com.utils.mongo");

	public static MongoUtils getInstance() {
		MongoUtils utils = Singleton.get(MongoUtils.class);
		return utils;
	}

	public Datastore getDB() {
		return datastore;
	}

	public MongoUtils() {
		new Thread(new Runnable() {

			@Override
			public void run() {

				final Morphia morphia = new Morphia();

				// tell Morphia where to find your classes
				// can be called multiple times with different packages or
				// classes
				// morphia.mapPackage(PACKAGE);

				// create the Datastore connecting to the default port on the
				// local host
				MongoClient client = new MongoClient(HOST);
				datastore = morphia.createDatastore(client, SCHEME);
				datastore.ensureIndexes();
				System.out.println("start mongo");
			}
		}).start();
	}

	public void deleteById(String id) {
		// System.out.println(id);
		// final Query<PxlmPaidanItem> query =
		// datastore.createQuery(PxlmPaidanItem.class).filter("id =", id);
		// System.out.println(query.count());
		// datastore.delete(query);
	}

	public void add() {
		// PXLMSupport support = new PXLMSupport();
		// support.setName("cjw " + DateUtil.now());
		// datastore.save(support);
	}

	public void query() {
		// final Query<PXLMSupport> query =
		// datastore.createQuery(PXLMSupport.class);
		// final List<PXLMSupport> employees = query.asList();
		// // datastore.delete(query);
		// for (PXLMSupport pxlmSupport : employees) {
		// System.out.println(JsonKit.toJson(pxlmSupport));
		// }
	}

	public Key<Object> save(Object model) {
		try {
			return datastore.save(model);
		} catch (Exception e) {
			return null;
		}
	}

	public void save() {
		// PXLMSupport support = new PXLMSupport();
		// support.setName("cjw " + DateUtil.now());
		// support.setAuthor("cjw");
		// datastore.save(support);
		// System.out.println(support.getId() + " ==");
		// PxlmPaidanItem paidanItem = new PxlmPaidanItem();
		// paidanItem.setTitle("fff");
		// paidanItem.setPaidanId(support.getId());
		// datastore.save(paidanItem);

		// List<PxlmPaidanItem> array = support.getDirectReports();
		// if (array == null) {
		// array = new ArrayList<>();
		// }
		// array.add(paidanItem);
		// support.setDirectReports(array);
	}

}
